//
//  ClockBgView.m
//  test02
//
//  Created by lzh on 2020/10/23.
//  Copyright © 2020 NO. All rights reserved.
//

#import "ClockBgView.h"
#define LINE_WIDTH_NORMAL 8 //短刻度
#define LINE_WIDTH_LENGTH 16
#define ALL_SACLE 60 //总刻度

#define angle2radion(angle) ((angle) / 180.0 * M_PI)

// 1秒6度(秒针)

#define perSecondA 6

// 1分钟6度(分针)

#define perMintueA 6

// 1小时30度（时针）

#define perHourA 30

// 每分钟时针转(30 / 60 °)

#define perMinHourA 0.5
#import "WeakProxy.h"
@interface ClockBgView()

@property(nonatomic,strong)CAShapeLayer * scondLayer;
@property(nonatomic,strong)CAShapeLayer * minuteLayer;
@property(nonatomic,strong)CAShapeLayer * hourLayer;
@property(nonatomic,strong)NSTimer * timer;

@end
@implementation ClockBgView


-(instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
#pragma mark 定时器
                    
        WeakProxy * prox =  [WeakProxy alloc];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target: [prox initWithTarget:self] selector:@selector(timeChange) userInfo:nil repeats:YES];
            
        [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
    
    return self;
}
-(void)drawRect:(CGRect)rect{

#define 创建表盘60个刻度
    
    
    for (int i=1; i<= ALL_SACLE; i++) {

        CAShapeLayer * line = [CAShapeLayer layer];
        
        if (i%5==0) {
            line.lineWidth = LINE_WIDTH_LENGTH;
        }else{
            line.lineWidth = LINE_WIDTH_NORMAL;

        }
        
        NSArray * arr = @[@"0",@"2",@"1",@"12",@"11",@"10",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2",@"1"];
        if (i%5==0) {// 添加数字
            CGPoint point =  [self calcCircleCoordinateWithCenter:CGPointMake(rect.size.width/2.0, rect.size.height/2.0) andWithAngle:i*6 andWithRadius:rect.size.width/2.0-30];
                
                CATextLayer * text = [CATextLayer layer];
//                text.backgroundColor = [UIColor orangeColor].CGColor;
                
                text.foregroundColor = [UIColor purpleColor].CGColor;
            // 字体名称、大小
//               UIFont *font = [UIFont systemFontOfSize:8.0];
//               CFStringRef fontName = (__bridge CFStringRef)font.fontName;
//               CGFontRef fontRef =CGFontCreateWithFontName(fontName);
//               text.font = fontRef;
               text.fontSize = 20;
               text.alignmentMode = kCAAlignmentCenter;
                text.string = [NSString stringWithFormat:@"%@",arr[i/5]];
            // 渲染分辨率-重要，否则显示模糊
                text.contentsScale = [UIScreen mainScreen].scale;
                text.bounds = CGRectMake(0, 0, 22, 20);
                text.position = point;
                [self.layer addSublayer:text];
        }
        line.fillColor = [UIColor clearColor].CGColor;
        line.strokeColor = [UIColor brownColor].CGColor;
        CGFloat perAngle= 2 * M_PI / ALL_SACLE;//每一刻 多少度
        CGFloat start = perAngle*i;
        CGFloat move = perAngle/5;//移动度数
        UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(rect.size.width/2.0, rect.size.height/2.0) radius:rect.size.width/2.0 -LINE_WIDTH_LENGTH/2 startAngle:start endAngle:start + move clockwise:YES];

        line.path = path.CGPath;

        [self.layer addSublayer:line];
        
    }
#define 时分秒
    [self.layer addSublayer:self.hourLayer];

    [self.layer addSublayer:self.minuteLayer];
    
     [self.layer addSublayer:self.scondLayer];
    
}
// 系统绘制 会走这里 看是否有delegate view默认是layer的代理
//   只要写 就会走（前提必须写drawRect）    里面掉用【super drawLayer incontext】就会走drawRect
//   不写会走系统的[CALayer drawInContext]
#define 外圈圆
-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
    
    CAShapeLayer * ca_layer = (CAShapeLayer *)layer;
   
    UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(layer.bounds.size.width/2.0, layer.bounds.size.height/2.0) radius:layer.bounds.size.width/2.0 startAngle:0 endAngle:2*M_PI clockwise:YES];
    
    ca_layer.fillColor = [UIColor blackColor].CGColor;
    ca_layer.strokeColor = [UIColor redColor].CGColor;
    ca_layer.lineWidth = 2.0;
    ca_layer.path = path.CGPath;
    [super drawLayer:layer inContext:ctx];

}

+(Class)layerClass{
    
    return CAShapeLayer.class;
}


-(CAShapeLayer *)scondLayer{
    
    if (!_scondLayer) {
        _scondLayer = [CAShapeLayer layer];
        _scondLayer.anchorPoint = CGPointMake(0.5, 1);
        _scondLayer.backgroundColor = [UIColor redColor].CGColor;
        _scondLayer.position = CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0);
        _scondLayer.bounds = CGRectMake(0, 0, 1.5, self.bounds.size.width/2.0-50);
    }
    
    return _scondLayer;
}

-(CAShapeLayer *)hourLayer{
    
    if (!_hourLayer) {
        _hourLayer = [CAShapeLayer layer];
        
        _hourLayer.anchorPoint = CGPointMake(0.5, 1);
               _hourLayer.backgroundColor = [UIColor whiteColor].CGColor;
               _hourLayer.position = CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0);
               _hourLayer.bounds = CGRectMake(0, 0, 1.5, self.bounds.size.width/2.0-70);
    }
    
    return _hourLayer;
}

-(CAShapeLayer *)minuteLayer{
    
    if (!_minuteLayer) {
        _minuteLayer = [CAShapeLayer layer];
        _minuteLayer.anchorPoint = CGPointMake(0.5, 1);
                      _minuteLayer.backgroundColor = [UIColor yellowColor].CGColor;
                      _minuteLayer.position = CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0);
                      _minuteLayer.bounds = CGRectMake(0, 0, 1.5, self.bounds.size.width/2.0-60);
    }
    
    return _minuteLayer;
}

- (void)timeChange{
    
    // 获取当前系统时间
    
    NSCalendar * calender = [NSCalendar currentCalendar];
    
    NSDateComponents * cmp = [calender components:NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour  fromDate:[NSDate date]];
    
    CGFloat second = cmp.second;
    
    CGFloat secondA = (second * perSecondA) ;
    
    NSInteger minute = cmp.minute;
    
    CGFloat mintuteA = minute * perMintueA ;
    
    NSInteger hour = cmp.hour;
    
    CGFloat hourA = hour * perHourA  + minute * perMinHourA;
    
    self.scondLayer.transform = CATransform3DMakeRotation(angle2radion(secondA), 0, 0, 1);

    self.minuteLayer.transform = CATransform3DMakeRotation(angle2radion(mintuteA), 0, 0, 1);
    
    self.hourLayer.transform = CATransform3DMakeRotation(angle2radion(hourA), 0, 0, 1);
}
/**
--------------------------------------------------------------
功能说明
--------------------------------------------------------------
根据IOS视图中圆组件的中心点(x,y)、半径(r)、圆周上某一点与圆心的角度这3个
条件来计算出该圆周某一点在IOS中的坐标(x2,y2)。

注意：
（1）IOS坐标体系与数学坐标体系有差别，因此不能完全采用数学计算公式。
（2）数学计算公式：
    x2=x+r*cos(角度值*PI/180)
    y2=y+r*sin(角度值*PI/180)
（3）IOS中计算公式：
    x2=x+r*cos(角度值*PI/180)
    y2=y-r*sin(角度值*PI/180)

--------------------------------------------------------------
参数说明
--------------------------------------------------------------
@param (CGPoint) center

圆圈在IOS视图中的中心坐标，即该圆视图的center属性

@param (CGFloat) angle
角度值，是0～360之间的值。
注意：
（1）请使用下面坐标图形进行理解。
（2）角度是逆时针转的，从x轴中心(0,0)往右是0度角（或360度角），往左是180度角，往上是90度角，往下是270度角。

       (y)
        ^
        |
        |
        |
        |
-----------------> (x)
        |(0,0)
        |
        |
        |

@param (CGFloat) radius
圆周半径
*/

#pragma mark 计算圆圈上点在IOS系统中的坐标
-(CGPoint)calcCircleCoordinateWithCenter:(CGPoint) center  andWithAngle : (CGFloat) angle andWithRadius: (CGFloat) radius{
    CGFloat x2 = radius*cosf(angle*M_PI/180);
    CGFloat y2 = radius*sinf(angle*M_PI/180);
    return CGPointMake(center.x+x2, center.y-y2);
}

-(void)dealloc{
    
    [self.timer invalidate];
    self.timer = nil;
}

@end
